package com.webber.demo.common.utils;

import java.text.DecimalFormat;

import org.springframework.web.multipart.MultipartFile;

/**
 * 文件工具类，处理文件名前缀和后缀，以及文件大小
 * @author mhl
 *
 */
public class FileUtil{
	/**
	 * 获取文件扩展名
	 * @param fileName
	 * @return
	 */
   public static String getFileExt(String fileName){
     String ext = "";
     if (!StringUtil.isBlank(fileName)) {
       ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
     }
     return StringUtil.trim(ext);
   }
   /**
    * 获取文件前缀
    * @param fileName
    * @return
    */
   public static String getFilePrefix(String fileName){
     String filePrefix = "";
     if (!StringUtil.isBlank(fileName)) {
       filePrefix = fileName.substring(0, fileName.lastIndexOf("."));
     }
     return StringUtil.trim(filePrefix);
   }
   /**
    * 获取文件后缀
    * @param fileName
    * @return
    */
   public static String getFileSuffix(String fileName){
	   if(fileName==null) {
		   return null;
	   }
	   String fileSuffix = "";
	   if(!StringUtil.isBlank(fileName)){
		   fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	   }
	   return StringUtil.trim(fileSuffix);
   }
   /**
    * 获取文件大小
    * @param mFile
    * @return
    */
   public static String getFileSize(MultipartFile mFile){
	   String size = "";
		    long fileS = mFile.getSize();
		      DecimalFormat df = new DecimalFormat("#.00"); 
		           if (fileS < 1024) {
		               size = df.format((double) fileS) + "BT";
		           } else if (fileS < 1048576) {
		               size = df.format((double) fileS / 1024) + "KB";
		           } else if (fileS < 1073741824) {
		               size = df.format((double) fileS / 1048576) + "MB";
		           } else {
		               size = df.format((double) fileS / 1073741824) +"GB";
		           }
		           System.out.println(size);
	   return size;
   }

}

